package com.example.guiguiapplicatio.fragment;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.icu.util.Calendar;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.example.guiguiapplicatio.api.Interface.Api;
import com.example.guiguiapplicatio.R;
import com.example.guiguiapplicatio.databinding.FragmentFollowUpBinding;
import com.example.guiguiapplicatio.databindingBean.followup.ListFollowupWith;
import com.example.guiguiapplicatio.fragment.followup.adapter.FlowUpFragmentAdapter;
import com.example.guiguiapplicatio.util.ResponseBody;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public class FollowUpragment extends Fragment {

    // TODO: Rename and change types of parameters
    private FragmentFollowUpBinding binding;
    private FlowUpFragmentAdapter adapter;
    private TabHost tabHost;
    private int SHOW_SIFT = 0;

    private ArrayList<Integer> idList = new ArrayList<Integer>();
    private int tmpSelectedId1;
    private int tmpSelectedId2;
    private int tmpSelectedId3;
    //url参数
    private Integer PARAM_PAGE_BEGIN = 0;
    private Integer PARAM_PAGE_SIZE = 10;
    private String PARAM_TIME_LIMIT = null;
    private String PARAM_DATEA = null, PARAM_DATEB = null;
    private Integer PARAM_STATE = null;
    private String PARAM_TYPE = null;
    private String PARAM_SEARCH_STRING = null;
    //url参数
    private Retrofit retrofit;
    private Api api;
    private static OkHttpClient client = null;
    private String str, str1;
    List<ListFollowupWith> NOW_DATA_LIST = new ArrayList<>();

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        client = new OkHttpClient.Builder().
//                 readTimeout(30, TimeUnit.SECONDS).
//                writeTimeout(30, TimeUnit.SECONDS).
        connectTimeout(6, TimeUnit.SECONDS).build();//用于设置请求超时等限制时间

        retrofit = new Retrofit.Builder()
                .client(client)
                .baseUrl(getString(R.string.api))
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        api = retrofit.create(Api.class);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        binding = FragmentFollowUpBinding.inflate(inflater, container, false);
        View view = binding.getRoot();

        binding.flowUpList.setLayoutManager(new LinearLayoutManager(binding.getRoot().getContext()));

        initData();
        siftTrans();
        flashAndLoad();
        jumpToNew();
        setSearchBar();
        return view;
    }


    private void initData() {
        PARAM_PAGE_BEGIN=0;
        Call<ResponseBody<List<ListFollowupWith>>> objectCall =
                api.getFollowUpList(PARAM_PAGE_BEGIN, PARAM_PAGE_SIZE, null, null, null, null, null, null);
        objectCall.enqueue(new Callback<ResponseBody<List<ListFollowupWith>>>() {
            @Override
            public void onResponse(Call<ResponseBody<List<ListFollowupWith>>> call, Response<ResponseBody<List<ListFollowupWith>>> response) {
                ResponseBody<List<ListFollowupWith>> responseBody = response.body();
                if (responseBody != null) {

                    NOW_DATA_LIST.clear();
                    NOW_DATA_LIST = responseBody.getData();
                    adapter = new FlowUpFragmentAdapter(NOW_DATA_LIST);
                    binding.flowUpList.setAdapter(adapter);
                    countFollowup(NOW_DATA_LIST);

                    for (int i = 0; i < responseBody.getData().size(); i++) {
                        Log.e("responseBody.getData()", "responseBody.getData()   :" + responseBody.getData().get(i).getPatientName());
                    }
                }else {
                    NOW_DATA_LIST.clear();
                    adapter = new FlowUpFragmentAdapter(NOW_DATA_LIST);
                    binding.flowUpList.setAdapter(adapter);
                }

            }

            @Override
            public void onFailure(Call<ResponseBody<List<ListFollowupWith>>> call, Throwable t) {
                Log.e("responseBody.onFailure", "onFailure  :" + t);

                NOW_DATA_LIST.clear();
                adapter = new FlowUpFragmentAdapter(NOW_DATA_LIST);
                binding.flowUpList.setAdapter(adapter);
                if (getContext()!=null){
                    Toast.makeText(getContext(), "网络连接有误", Toast.LENGTH_LONG).show();
                }
            }
        });


    }

    private void setSearchBar() {
        if (  binding.etSearchtext.getText().length()==0||binding.etSearchtext.getText()==null){
            binding.removeTextBtn.setVisibility(View.GONE);
        }
        binding.removeTextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.etSearchtext.setText("");
            }
        });
        binding.etSearchtext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    binding.removeTextBtn.setVisibility(View.GONE);
                } else {
                    binding.removeTextBtn.setVisibility(View.VISIBLE);
                }
            }
        });

        binding.searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (binding.etSearchtext.getText().equals("")){
                    Toast.makeText(getContext(), "请输入查询内容", Toast.LENGTH_LONG).show();
                }else {
                    PARAM_SEARCH_STRING= String.valueOf(binding.etSearchtext.getText());
                    PARAM_PAGE_BEGIN=0;
                    Call<ResponseBody<List<ListFollowupWith>>> objectCall =
                            api.getFollowUpList(PARAM_PAGE_BEGIN, PARAM_PAGE_SIZE, PARAM_TIME_LIMIT, PARAM_DATEA, PARAM_DATEB, PARAM_STATE, PARAM_TYPE, PARAM_SEARCH_STRING);
                    objectCall.clone().enqueue(new Callback<ResponseBody<List<ListFollowupWith>>>() {
                        @Override
                        public void onResponse(Call<ResponseBody<List<ListFollowupWith>>> call, Response<ResponseBody<List<ListFollowupWith>>> response) {
                            ResponseBody<List<ListFollowupWith>> responseBody = response.body();
                            if (responseBody != null) {

                                NOW_DATA_LIST.clear();
                                for (int i = 0; i < responseBody.getData().size(); i++) {
                                    NOW_DATA_LIST.add(responseBody.getData().get(i));
                                }
                                adapter.notifyDataSetChanged();
                                countFollowup(NOW_DATA_LIST);

                                for (int i = 0; i < responseBody.getData().size(); i++) {
                                    Log.e("responseBody.getData()", "responseBody.getData()   :" + responseBody.getData().get(i).getPatientName());
                                }
                            }
                        }

                        @Override
                        public void onFailure(Call<ResponseBody<List<ListFollowupWith>>> call, Throwable t) {
                            Log.e("responseBody.onFailure", "onFailure  :" + t);
                            Toast.makeText(getContext(), "网络连接有误", Toast.LENGTH_LONG).show();
                        }
                    });
                }

            }
        });

    }

    private void jumpToNew() {
        binding.flowUpFab.setOnClickListener(Navigation.createNavigateOnClickListener(R.id.action_navigation_flow_up_to_newFollowUpFragment));
    }


    private void siftTrans() {
        binding.tabhost.setVisibility(View.INVISIBLE);
        binding.ziDingyiLayout.setVisibility(View.INVISIBLE);

        tabHost = binding.tabhost;

        tabHost.setup();
        TabHost.TabSpec myTab1 = tabHost.newTabSpec("随访时间"); //定义TabSpec
        myTab1.setIndicator("随访时间"); //设置选项文字
        myTab1.setContent(R.id.flow_up_time_group);  //设置显示的组件
        tabHost.addTab(myTab1); //增加选项

        TabHost.TabSpec myTab2 = tabHost.newTabSpec("状态");//定义TabSpec
        myTab2.setIndicator("状态").setContent(R.id.come_from_group); //设置显示的组件
        tabHost.addTab(myTab2);  //增加选项

        TabHost.TabSpec myTab3 = tabHost.newTabSpec("所属人群");//定义TabSpec
        myTab3.setIndicator("所属人群").setContent(R.id.affiliation_group); //设置显示的组件
        tabHost.addTab(myTab3);  //增加选项
        tabHost.setCurrentTab(0);
        for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
            View a = tabHost.getTabWidget().getChildAt(i);
            TextView tv = (TextView) a.findViewById(android.R.id.title);
            tv.setTextSize(20);

        }


        binding.flowUpSiftButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (SHOW_SIFT == 0) {
                    SHOW_SIFT = 1;
                    binding.tabhost.setVisibility(View.VISIBLE);
                } else {
                    SHOW_SIFT = 0;
                    binding.tabhost.setVisibility(View.INVISIBLE);
                }
            }
        });


        binding.flowUpTimeGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == binding.ziDingyi.getId()) {
                    binding.ziDingyiLayout.setVisibility(View.VISIBLE);
                } else {
                    binding.ziDingyiLayout.setVisibility(View.INVISIBLE);
                }
                tmpSelectedId1 = checkedId;
            }
        });

        binding.comeFromGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                tmpSelectedId2 = checkedId;

            }
        });

        binding.affiliationGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                tmpSelectedId3 = checkedId;
            }
        });

        dateSelect();//自定义日期选择
        siftAndRemake();//重置和确定筛选
    }

    private void dateSelect() {
        binding.selectDateBegan.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("ResourceType")
            @Override
            public void onClick(View v) {
                DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        month = month + 1;
                        str = year + "年" + month + "月" + dayOfMonth + "日";//把日期变成字符串格式显示出来
                        binding.selectDateBeganEdit.setText(str);//文本框显示的内容设置成经过逻辑处理后的日期
                    }
                }; Calendar calendar = Calendar.getInstance();
                new DatePickerDialog(getContext(), 5, onDateSetListener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
            }
        });
        binding.selectDateEnd.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("ResourceType")
            @Override
            public void onClick(View v) {
                DatePickerDialog.OnDateSetListener onDateSetListener = new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        month = month + 1;
                        str1 = year + "年" + month + "月" + dayOfMonth + "日";//把日期变成字符串格式显示出来
                        binding.selectDateEndEdit.setText(str1);//文本框显示的内容设置成经过逻辑处理后的日期
                    }
                }; Calendar calendar = Calendar.getInstance();
                new DatePickerDialog(getContext(), 5, onDateSetListener, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();
            }
        });
    }

    private void siftAndRemake() {
        binding.searchSift.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                idList.clear();
                idList.add(tmpSelectedId1);
                idList.add(tmpSelectedId2);
                idList.add(tmpSelectedId3);

                Boolean HAVE_TAG = false;
                for (int i = 0; i < idList.size(); i++) {
                    if (idList.get(i) != 0 && idList.get(i) != -1) {
                        HAVE_TAG = true;
                    }
                }
                if (HAVE_TAG == false) {
//                    Toast.makeText(getContext(), "无选项，执行刷新", Toast.LENGTH_LONG).show();
                    binding.tabhost.setVisibility(View.GONE);
                    PARAM_PAGE_BEGIN=0;
                    Call<ResponseBody<List<ListFollowupWith>>> objectCall =
                            api.getFollowUpList(PARAM_PAGE_BEGIN, PARAM_PAGE_SIZE, PARAM_TIME_LIMIT, PARAM_DATEA, PARAM_DATEB, PARAM_STATE, PARAM_TYPE, PARAM_SEARCH_STRING);
                    objectCall.clone().enqueue(new Callback<ResponseBody<List<ListFollowupWith>>>() {
                        @Override
                        public void onResponse(Call<ResponseBody<List<ListFollowupWith>>> call, Response<ResponseBody<List<ListFollowupWith>>> response) {
                            ResponseBody<List<ListFollowupWith>> responseBody = response.body();
                            if (responseBody != null) {

                                NOW_DATA_LIST.clear();
                                for (int i = 0; i < responseBody.getData().size(); i++) {
                                    NOW_DATA_LIST.add(responseBody.getData().get(i));
                                }
                                adapter.notifyDataSetChanged();
                                countFollowup(NOW_DATA_LIST);

                            }
                        }

                        @Override
                        public void onFailure(Call<ResponseBody<List<ListFollowupWith>>> call, Throwable t) {
                            binding.flowUpRefreshLayout.finishRefresh(false/*,false*/);
                            if (getContext()!=null){
                                Toast.makeText(getContext(), "网络连接有误", Toast.LENGTH_LONG).show();
                                PARAM_PAGE_BEGIN=0;
                            }
                        }
                    });


                } else {//有选项

                    if (tmpSelectedId1 != 0 && tmpSelectedId1 != -1) {
                        RadioButton radioButton = getActivity().findViewById(tmpSelectedId1);
                        String tag = (String) radioButton.getText();
                        PARAM_TIME_LIMIT=tag;
                        if (tag.equals("自定义")) {

                            PARAM_DATEA = String.valueOf(binding.selectDateBeganEdit.getText());
                            PARAM_DATEB = String.valueOf(binding.selectDateEndEdit.getText());
                        }
                    }
                    if (tmpSelectedId2 != 0 && tmpSelectedId2 != -1) {
                        RadioButton radioButton = getActivity().findViewById(tmpSelectedId2);
                        String tag = (String) radioButton.getText();
                        if (tag.equals("草稿")){
                            PARAM_STATE=0;
                        }else PARAM_STATE=1;

                    }
                    if (tmpSelectedId3 != 0 && tmpSelectedId3 != -1) {
                        RadioButton radioButton = getActivity().findViewById(tmpSelectedId3);
                        String tag = (String) radioButton.getText();
                        PARAM_TYPE=tag;
                    }

//                    Toast.makeText(getContext(), "有选项，执行筛选", Toast.LENGTH_LONG).show();
                    binding.tabhost.setVisibility(View.GONE);
                    PARAM_PAGE_BEGIN=0;
                    Call<ResponseBody<List<ListFollowupWith>>> objectCall =
                            api.getFollowUpList(PARAM_PAGE_BEGIN, PARAM_PAGE_SIZE, PARAM_TIME_LIMIT, PARAM_DATEA, PARAM_DATEB, PARAM_STATE, PARAM_TYPE, PARAM_SEARCH_STRING);
                    objectCall.clone().enqueue(new Callback<ResponseBody<List<ListFollowupWith>>>() {
                        @Override
                        public void onResponse(Call<ResponseBody<List<ListFollowupWith>>> call, Response<ResponseBody<List<ListFollowupWith>>> response) {
                            ResponseBody<List<ListFollowupWith>> responseBody = response.body();
                            if (responseBody != null) {

                                NOW_DATA_LIST.clear();
                                for (int i = 0; i < responseBody.getData().size(); i++) {
                                    NOW_DATA_LIST.add(responseBody.getData().get(i));
                                }
                                adapter.notifyDataSetChanged();
                                countFollowup(NOW_DATA_LIST);

                            }
                        }

                        @Override
                        public void onFailure(Call<ResponseBody<List<ListFollowupWith>>> call, Throwable t) {
                            Log.e("responseBody.onFailure", "onFailure  :" + t);
                            if (getContext()!=null){
                                Toast.makeText(getContext(), "网络连接有误", Toast.LENGTH_LONG).show();
                                PARAM_PAGE_BEGIN=0;
                            }

                        }
                    });
                }//有选项
            }
        });
        binding.searchRemake.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.comeFromGroup.clearCheck();
                binding.affiliationGroup.clearCheck();
                binding.flowUpTimeGroup.clearCheck();
                idList.clear();
                tmpSelectedId1 = 0;
                tmpSelectedId2 = 0;
                tmpSelectedId3 = 0;

                PARAM_DATEA=null;
                PARAM_DATEB=null;
                PARAM_TIME_LIMIT=null;
                PARAM_STATE=null;
                PARAM_TYPE=null;
                Toast.makeText(getContext(), "已清空选项", Toast.LENGTH_LONG).show();
            }
        });
    }

    private void flashAndLoad() {

        binding.flowUpRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                binding.flowUpRefreshLayout.finishRefresh(100/*,false*/);//传入false表示刷新失败
                PARAM_PAGE_BEGIN=0;
                Call<ResponseBody<List<ListFollowupWith>>> objectCall =
                        api.getFollowUpList(PARAM_PAGE_BEGIN, PARAM_PAGE_SIZE, PARAM_TIME_LIMIT, PARAM_DATEA, PARAM_DATEB, PARAM_STATE, PARAM_TYPE, PARAM_SEARCH_STRING);
                objectCall.clone().enqueue(new Callback<ResponseBody<List<ListFollowupWith>>>() {
                    @Override
                    public void onResponse(Call<ResponseBody<List<ListFollowupWith>>> call, Response<ResponseBody<List<ListFollowupWith>>> response) {
                        ResponseBody<List<ListFollowupWith>> responseBody = response.body();
                        if (responseBody != null) {

                            NOW_DATA_LIST.clear();
                            for (int i = 0; i < responseBody.getData().size(); i++) {
                                NOW_DATA_LIST.add(responseBody.getData().get(i));
                            }
                            adapter.notifyDataSetChanged();
                            countFollowup(NOW_DATA_LIST);

                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody<List<ListFollowupWith>>> call, Throwable t) {
                        binding.flowUpRefreshLayout.finishRefresh(false/*,false*/);
                        if (getContext()!=null){
                            Toast.makeText(getContext(), "网络连接有误", Toast.LENGTH_LONG).show();
                            PARAM_PAGE_BEGIN=0;
                        }

                    }
                });
            }
        });
        binding.flowUpRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                binding.flowUpRefreshLayout.finishLoadMore(600/*,false*/);//传入false表示加载失败
                PARAM_PAGE_BEGIN=NOW_DATA_LIST.size();
                Call<ResponseBody<List<ListFollowupWith>>> objectCall =
                        api.getFollowUpList(PARAM_PAGE_BEGIN, PARAM_PAGE_SIZE, PARAM_TIME_LIMIT, PARAM_DATEA, PARAM_DATEB, PARAM_STATE, PARAM_TYPE, PARAM_SEARCH_STRING);
                objectCall.clone().enqueue(new Callback<ResponseBody<List<ListFollowupWith>>>() {
                    @Override
                    public void onResponse(Call<ResponseBody<List<ListFollowupWith>>> call, Response<ResponseBody<List<ListFollowupWith>>> response) {
                        ResponseBody<List<ListFollowupWith>> responseBody = response.body();
                        if (responseBody != null) {

                            for (int i = 0; i < responseBody.getData().size(); i++) {
                                NOW_DATA_LIST.add(responseBody.getData().get(i));
                            }
                            adapter.notifyDataSetChanged();
                            binding.flowUpRefreshLayout.finishRefresh(true/*,false*/);
                            countFollowup(NOW_DATA_LIST);

                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody<List<ListFollowupWith>>> call, Throwable t) {
                        binding.flowUpRefreshLayout.finishLoadMore(false/*,false*/);
                        if (getContext()!=null){
                            Toast.makeText(getContext(), "网络连接有误", Toast.LENGTH_LONG).show();
                            PARAM_PAGE_BEGIN=0;
                        }

                    }
                });
            }
        });

    }

    @Override
    public void onResume() {
        BottomNavigationView bottomNavigationView = requireActivity().findViewById(R.id.nav_view);
        bottomNavigationView.setVisibility(View.VISIBLE);
        if (  binding.etSearchtext.getText().length()==0||binding.etSearchtext.getText()==null){
            binding.removeTextBtn.setVisibility(View.GONE);
        }
        

        super.onResume();
    }

    private void countFollowup(List<ListFollowupWith> list) {
        int drafts = 0;
        int formal = 0;

        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getFollowUp().getState().equals(0)) {
                drafts++;
            } else {
                formal++;
            }
        }
        binding.flowUpInfoDrafts.setText("草稿数：" + drafts);
        binding.flowUpInfoFormal.setText("正式随访数：" + formal);
    }


}